import { router } from '@/router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth.ts';
import { usePermissionStoreWithOut } from '@/store/modules/permission.ts';
import { useUserStoreWithOut } from '@/store/modules/user.ts';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/register', '/reset-password'];

export default function permissionsGuard() {
  router.beforeEach((to, from, next) => {
    NProgress.start();
    if (getToken()) {
      /* has token*/
      if (to.path === '/login') {
        next();
      } else {
        document.title = to.meta.title
          ? (to.meta.title as string)
          : (__APP_ENV__.VITE_APP_TITLE as string);
        const userStore = useUserStoreWithOut();
        // 如果获取到用户角色权限为空
        const userRoles = userStore.roles;
        if (userRoles.length === 0) {
          const permissionStore = usePermissionStoreWithOut();
          // 判断当前用户是否已拉取完user_info信息
          userStore
            .GetInfo()
            .then(() => {
              permissionStore.GenerateRoutes().then((accessRoutes: any) => {
                // 根据roles权限生成可访问的路由表
                accessRoutes.forEach((item: any) => {
                  router.addRoute(item);
                });
                // 防止404路由在接口返回路由表之前就进行了404页面的跳转
                if (to.redirectedFrom) {
                  next({ ...to.redirectedFrom, replace: true });
                } else {
                  next({ ...to, replace: true });
                }
              });
            })
            .catch((err) => {
              userStore.LogOut().then(() => {
                if (to.redirectedFrom) {
                  next(`/login?redirect=${encodeURIComponent(to.redirectedFrom.fullPath)}`); // 否则全部重定向到登录页
                } else {
                  next(`/login`);
                }
              });
            });
        } else {
          next();
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        // 在免登录白名单，直接进入
        next();
      } else {
        if (to.redirectedFrom) {
          next(`/login?redirect=${encodeURIComponent(to.redirectedFrom.fullPath)}`); // 否则全部重定向到登录页
        } else {
          next(`/login`);
        }
      }
    }
  });

  router.afterEach((to, from, failure) => {
    NProgress.done();
  });
  console.log('✨路由权限守卫注册成功✨');
}
